#!/bin/sh
#################################################################################
# 任意目录下
#################################################################################
cur_dir=$(cd `dirname $0`; pwd)
soft_dir=$cur_dir
cd $cur_dir
db_flag=s_8.0.34
docker_image_version=3.2.0
if [[ -n $1 ]];then
  docker_image_version=$1
fi
docker_image_flag=capp_db_${docker_image_version}
echo "docker image:$docker_image_flag"

cd $soft_dir/db
if [[ -f "db.sql" ]];then
  rm -rf db.sql
fi
tar xvf db.tar.gz
initSQL=$soft_dir/db/db.sql
if [[ -f init.sql ]];then
  rm -rf init.sql
fi
##################### 如果是MySQL 8.0 修改配置################
if [[ $db_flag == "s_8.0.34" ]];then
  echo "">conf.sql
  echo "set global collation_connection = utf8mb4_general_ci;"              >> conf.sql
  echo "set global default_collation_for_utf8mb4 = utf8mb4_general_ci;"     >> conf.sql
  echo "set persist default_collation_for_utf8mb4 = utf8mb4_general_ci;"    >> conf.sql
  echo "set persist collation_connection = utf8mb4_general_ci;"             >> conf.sql
else
  #mysql 5.7.x
  echo "set global collation_connection = utf8_general_ci;"                 >> conf.sql
fi
cp $initSQL init.sql

echo "grant all on *.* to app;">tooldb.sql
echo "flush privileges;">>tooldb.sql
cat << EOF > init.sh
#!/bin/bash
echo "start to init">>/tmp/init.log
user=root
pwd=\`env|grep MYSQL_ROOT_PASSWORD|awk -F "=" '{print \$NF}'\`
db=\`env|grep MYSQL_DATABASE|awk -F "=" '{print \$NF}'\`
appMode=\`env|grep APP_MODE|awk -F "=" '{print \$NF}'\`
mysql -uroot -p\$pwd \$db < /conf.sql 2>/dev/null
mysql -uroot -p\$pwd \$db < /init.sql 2>/dev/null
mysql -uroot -p\$pwd \$db < /tooldb.sql 2>/dev/null
exit 0
EOF
#docker-entrypoint-initdb.d 执行顺序
cat << EOF > Dockerfile
FROM registry.cn-hangzhou.aliyuncs.com/lank/mysql:$db_flag
MAINTAINER DB
ADD conf.sql       /
ADD init.sql       /
ADD tooldb.sql     /
ADD init.sh        /docker-entrypoint-initdb.d
RUN chmod +x       /docker-entrypoint-initdb.d/init.sh
EOF
docker build ./ -t registry.cn-hangzhou.aliyuncs.com/lank/mysql:$docker_image_flag
if [[ -f init.sql ]];then
  rm -rf init.sql
  rm -rf conf.sql
  rm -rf tooldb.sql
fi
rm -rf Dockerfile
rm -rf init.sh
exit 0




